package com.warmheart.base.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.warmheart.core.util.cache.AreaCacheService;
import com.warmheart.core.util.cache.ConfigCacheService;
import com.warmheart.core.util.cache.DictCacheService;
import com.warmheart.entity.sys.SysAreaBase;
import com.warmheart.model.AreaInfoModel;
import com.warmheart.model.AreaTreeModel;
import com.warmheart.model.ConfigModel;
import com.warmheart.model.DictCache;
import com.warmheart.service.sys.ISysAreaBaseService;
import com.warmheart.service.sys.ISysDictBaseService;
import com.warmheart.service.sys.ISysConfigService;

/**
 * 
 * @ClassName: ApplicationStartedEventListener
 * @Description: 监听服务启动成功，执行一些预操作
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

    Logger logger = LoggerFactory.getLogger(ApplicationReadyEventListener.class);

    // 注入系统字典管理service
    @Autowired(required = false)
    private ISysDictBaseService sysDictBaseService;

    @Autowired(required = false)
    private ISysConfigService sysConfigService;

    @Autowired(required = false)
    private DictCacheService dictCacheService;

    @Autowired(required = false)
    private ConfigCacheService configCacheService;

    // 注入系统区域管理service
    @Autowired(required = false)
    private ISysAreaBaseService sysAreaBaseService;

    // 注入数据缓存service
    @Autowired(required = false)
    private AreaCacheService areaCacheService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        List<AreaTreeModel> treeModelList = sysAreaBaseService.getTreeModelList(new SysAreaBase());
        if (treeModelList == null) {
            treeModelList = new ArrayList<AreaTreeModel>();
        }
        Map<String, List<AreaTreeModel>> childrenMap = treeModelList.stream().collect(
                Collectors.groupingBy(AreaTreeModel::getParentValue));
        treeModelList.forEach(item -> {
            item.setChildren(childrenMap.get(item.getValue()) == null ? new ArrayList<AreaTreeModel>() : childrenMap
                    .get(item.getValue()));
        });
        List<AreaTreeModel> treeList = treeModelList.stream().filter(item -> "0".equals(item.getParentValue()))
                .collect(Collectors.toList());
        if (treeList == null) {
            treeList = new ArrayList<AreaTreeModel>();
        }
        // 指定省级和其下树形结构映射关系
        List<AreaInfoModel> provList = new ArrayList<AreaInfoModel>();
        Map<String, List<AreaTreeModel>> firstNextMap = new HashMap<String, List<AreaTreeModel>>();
        Map<String, List<AreaTreeModel>> secondNextMap = new HashMap<String, List<AreaTreeModel>>();
        Map<String, AreaInfoModel> areaMap = new HashMap<String, AreaInfoModel>();
        Map<String, String> areaNameMap = new HashMap<String, String>();
        // 省市树形结构
        List<AreaTreeModel> treeListTwo = new ArrayList<AreaTreeModel>();
        for (AreaTreeModel areaFirstTreeModel : treeList) {
            AreaInfoModel firstAreaInfoModel = new AreaInfoModel();
            firstAreaInfoModel.setCode(areaFirstTreeModel.getValue());
            firstAreaInfoModel.setProvCode(areaFirstTreeModel.getValue());
            firstAreaInfoModel.setProvName(areaFirstTreeModel.getLabel());
            areaMap.put(areaFirstTreeModel.getValue(), firstAreaInfoModel);
            areaNameMap.put(areaFirstTreeModel.getValue(), areaFirstTreeModel.getLabel());
            provList.add(firstAreaInfoModel);
            AreaTreeModel areaFirstModel = new AreaTreeModel();
            areaFirstModel.setChildren(new ArrayList<AreaTreeModel>());
            areaFirstModel.setLabel(areaFirstTreeModel.getLabel());
            areaFirstModel.setValue(areaFirstTreeModel.getValue());
            treeListTwo.add(areaFirstModel);
            if (areaFirstTreeModel.getChildren() != null && areaFirstTreeModel.getChildren().size() > 0) {
                for (AreaTreeModel areaSecondTreeModel : areaFirstTreeModel.getChildren()) {
                    AreaInfoModel secondAreaInfoModel = new AreaInfoModel();
                    secondAreaInfoModel.setCode(areaSecondTreeModel.getValue());
                    secondAreaInfoModel.setProvCode(areaFirstTreeModel.getValue());
                    secondAreaInfoModel.setProvName(areaFirstTreeModel.getLabel());
                    secondAreaInfoModel.setCityCode(areaSecondTreeModel.getValue());
                    secondAreaInfoModel.setCityName(areaSecondTreeModel.getLabel());
                    areaMap.put(areaSecondTreeModel.getValue(), secondAreaInfoModel);
                    areaNameMap.put(areaSecondTreeModel.getValue(), areaSecondTreeModel.getLabel());
                    AreaTreeModel areaSecondModel = new AreaTreeModel();
                    areaSecondModel.setLabel(areaSecondTreeModel.getLabel());
                    areaSecondModel.setValue(areaSecondTreeModel.getValue());
                    areaFirstModel.getChildren().add(areaSecondModel);

                    if (areaSecondTreeModel.getChildren() != null && areaSecondTreeModel.getChildren().size() > 0) {
                        for (AreaTreeModel areaThirdTreeModel : areaSecondTreeModel.getChildren()) {
                            AreaInfoModel thirdAreaInfoModel = new AreaInfoModel();
                            thirdAreaInfoModel.setCode(areaThirdTreeModel.getValue());
                            thirdAreaInfoModel.setProvCode(areaFirstTreeModel.getValue());
                            thirdAreaInfoModel.setProvName(areaFirstTreeModel.getLabel());
                            thirdAreaInfoModel.setCityCode(areaSecondTreeModel.getValue());
                            thirdAreaInfoModel.setCityName(areaSecondTreeModel.getLabel());
                            thirdAreaInfoModel.setDistrictCode(areaThirdTreeModel.getValue());
                            thirdAreaInfoModel.setDistrictName(areaThirdTreeModel.getLabel());
                            areaMap.put(areaThirdTreeModel.getValue(), thirdAreaInfoModel);
                            areaNameMap.put(thirdAreaInfoModel.getDistrictCode(), thirdAreaInfoModel.getDistrictName());
                        }
                    }
                    secondNextMap.put(areaSecondTreeModel.getValue(), areaSecondTreeModel.getChildren());
                }
            }
            firstNextMap.put(areaFirstTreeModel.getValue(), areaFirstTreeModel.getChildren());
        }
        logger.info("--------------开始缓存区域数据----------------");
        areaCacheService.putAllAreaInfo(treeList);
        areaCacheService.putTwoAreaInfo(treeListTwo);
        areaCacheService.putProvList(provList);
        areaCacheService.putProvNext(firstNextMap);
        areaCacheService.putCityNext(secondNextMap);
        areaCacheService.putAreaInfo(areaMap);
        areaCacheService.putAreaNameInfo(areaNameMap);
        logger.info("--------------区域数据缓存全部完成----------------");
        // 获取所有配置列表
        List<ConfigModel> configList = sysConfigService.getConfigForCaches();
        // 获取所有字典列表
        List<DictCache> dictList = sysDictBaseService.getDictForCaches();
        logger.info("配置数据刷入缓存 Start");
        configCacheService.putAllConfig(configList);
        logger.info("配置数据刷入缓存 End");
        logger.info("字典数据刷入缓存 Start");
        dictCacheService.putAllDictInfo(dictList);
        logger.info("字典数据刷入缓存 End");

    }

}
